# -*- coding: utf-8 -*-
# @Author: Tim Liu
# @Date: 2025-01-08
# @Last Modified by: Cursor
# @Last Modified time: 2025-01-08

# @Description: api endpoints for OSchema crud

from fastapi import APIRouter, Depends, Security
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from utils.response import SuccessResponse

from crewplus.helper.verify import get_api_key
from crewplus.apps.apikey.models.account_api_key import AccountApiKey

from core.database import db_getter
from core.dependencies import IdList
from core.exception import CustomException

from utils import status
from . import schemas, cruds, params, models

app = APIRouter()

###########################################################
#    OSchema API
###########################################################
@app.get("/schemas", summary="Get schema list")
async def get_schemas(p: params.OSchemaParams = Depends(), apikey: AccountApiKey = Security(get_api_key), db: AsyncSession = Depends(db_getter)):
    if apikey is None:
        raise CustomException("apiKey invalid", code=status.HTTP_ERROR)    
    
    model = models.OSchemaDB
    options = [joinedload(model.create_user)]
    schema = schemas.OSchemaFullOut
    datas, count = await cruds.OSchemaDal(db).get_datas(
        **p.dict(),
        v_options=options,
        v_schema=schema,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)


@app.post("/schema", summary="create one schema")
async def create_schema(data: schemas.OSchema, apikey: AccountApiKey = Security(get_api_key), db: AsyncSession = Depends(db_getter)):
    if apikey is None:
        raise CustomException("apiKey invalid", code=status.HTTP_ERROR)    
    
    data.create_user_id = apikey.user_id
    
    return SuccessResponse(await cruds.OSchemaDal(db).create_data(data=data))


@app.put("/schema/{data_id}", summary="update one schema detail")
async def change_schema(data_id: int, data: schemas.OSchema, apikey: AccountApiKey = Security(get_api_key), db: AsyncSession = Depends(db_getter)):
    if apikey is None:
        raise CustomException("apiKey invalid", code=status.HTTP_ERROR)    
        
    return SuccessResponse(await cruds.OSchemaDal(db).put_data(data_id, data))


@app.get("/schema/{data_id}", summary="get one schema detail by id")
async def get_schema(data_id: int, apikey: AccountApiKey = Security(get_api_key), db: AsyncSession = Depends(db_getter)):
    if apikey is None:
        raise CustomException("apiKey invalid", code=status.HTTP_ERROR)    
          
    schema = schemas.OSchemaFullOut
    return SuccessResponse(await cruds.OSchemaDal(db).get_data(data_id, v_schema=schema))


@app.delete("/schemas", summary="batch delete schemas", description="batch hard delete schemas from db")
async def delete_schemas(ids: IdList = Depends(), apikey: AccountApiKey = Security(get_api_key), db: AsyncSession = Depends(db_getter)):
    #TODO: check permission, account can only delete owned schemas after login
    if apikey is None:
        raise CustomException("apiKey invalid", code=status.HTTP_ERROR)    
                 
    await cruds.OSchemaDal(db).delete_datas(ids=ids.ids, v_soft=False)
    return SuccessResponse("Successfully deleted")
